import { useState, useEffect } from 'react';

function useCache(key: string, fetchFn: () => Promise<any>) {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const result = await fetchFn();
        setData(result);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    if (!window.caches || !window.caches.has(key)) {
      fetchData();
    } else {
      window.caches.match(key).then(response => {
        if (response) {
          response.json().then(setData);
          setLoading(false);
        } else {
          fetchData();
        }
      });
    }
  }, [key, fetchFn]);

  return { data, loading, error };
}

export default useCache;
